#include "pilha.h"

void init_stack(stack **my_stack) {
  (*my_stack)->top = NULL;
  (*my_stack)->bottom = NULL;
}

void add_task(stack **my_stack, task new_task) {
  
  cell_pointer new_cell = malloc(sizeof(cell));
  
  if ((*my_stack)->top == NULL) {
    (*my_stack)->bottom = new_cell;
    (*my_stack)->top = new_cell;
    (*my_stack)->bottom->down = NULL;
  }
  else {
    new_cell->down = (*my_stack)->top;
    (*my_stack)->top->up = new_cell;
    (*my_stack)->top = new_cell;
  }
  
  (*my_stack)->top->tarefa = new_task;
  (*my_stack)->top->up = NULL;
}


void pop_task(stack** my_stack) {
  
  if ((*my_stack)->top == (*my_stack)->bottom) {
    free((*my_stack)->top);
    (*my_stack)->top = (*my_stack)->bottom = NULL;
  }
  else {
    cell_pointer new_top = (*my_stack)->top->down;
    (*my_stack)->top->down = NULL;
    new_top->up = NULL;
    free((*my_stack)->top);
    
    (*my_stack)->top = new_top;
  }
}



void print_stack(const stack my_stack) {
  
  cell_pointer print_cell = my_stack.top;
  
  while (print_cell != NULL) {
    printf("%d\n", print_cell->tarefa.id);
    print_cell = print_cell->down;
  }
}

void destroy_stack(stack** my_stack) {
  
  cell_pointer print_cell = (*my_stack)->top;
  
  while (print_cell != NULL) {
    (*my_stack)->top = (*my_stack)->top->down;
    free(print_cell);
    print_cell = (*my_stack)->top;
  }
    
}
